﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IBM.Data.DB2.iSeries;

namespace Unimaq.FacturaDBS_Spring.Util
{
    public class ContextoDBAS400 : IDisposable
    {
        private iDB2Connection conexion;
        private iDB2Transaction tx;

        public static ContextoDBAS400 GetContexto()
        {
            ContextoDBAS400 ctx = new ContextoDBAS400();
            ctx.Load();
            return ctx;
        }

        public iDB2Transaction GetTx()
        {
            return tx;
        }

        public void Load()
        {
            string datosConexion = System.Configuration.ConfigurationManager.ConnectionStrings["AS400Connection"].ConnectionString;
            conexion = new iDB2Connection(datosConexion);
            conexion.Open();
        }

        public void Cerrar()
        {
            conexion.Close();
        }

        public iDB2Connection GetConexion()
        {
            return conexion;
        }

        public void LoadTransaction()
        {
            tx = conexion.BeginTransaction();
        }

        public void ConfirmarTx()
        {
            tx.Commit();
            tx = null;
        }

        public void RechazarTx()
        {
            tx.Rollback();
            tx = null;
        }

        public void Dispose()
        {
            if (tx != null)
            {
                tx.Rollback();
            }

            this.Cerrar();
        }
    }
}
